package com.atguigu.glkt.vod.service.impl;

import com.atguigu.ggkt.model.vod.Chapter;
import com.atguigu.ggkt.model.vod.Video;
import com.atguigu.ggkt.vo.vod.ChapterVo;
import com.atguigu.ggkt.vo.vod.VideoVo;
import com.atguigu.glkt.vod.mapper.ChapterMapper;
import com.atguigu.glkt.vod.service.ChapterService;
import com.atguigu.glkt.vod.service.VideoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author shaoxuan
 * @since 2022-07-12
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Autowired
    private VideoService videoService;


    @Override
    public List<ChapterVo> getNestedTreeList(String courseId) {
        LambdaQueryWrapper<Chapter> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Chapter::getCourseId,courseId);
        wrapper.orderByAsc(Chapter::getSort);
        List<Chapter> chapters = baseMapper.selectList(wrapper);
        
        LambdaQueryWrapper<Video> wrapperVideo = new LambdaQueryWrapper<>();
        wrapperVideo.eq(Video::getCourseId,courseId);
        List<Video> list = videoService.list(wrapperVideo);

        List<ChapterVo> res = new ArrayList<>();
        for (Chapter chapter : chapters) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter,chapterVo);
            res.add(chapterVo);
            for (Video video : list) {
                if (chapter.getId()==video.getChapterId()){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video,videoVo);
                    chapterVo.getChildren().add(videoVo);
                }
            }
        }
        return res;
    }

    @Override
    public void removeVideoByCourseId(Long id) {
        LambdaQueryWrapper<Chapter> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Chapter::getCourseId,id);
        baseMapper.delete(wrapper);
    }
}
